from django.shortcuts import render, redirect
from django.urls import reverse
from web.forms.wiki import WikiModelForm
from web import models
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from utils.encrypt import uid
from utils.tencent.cos import upload_file


def wiki(request, project_id):
    wiki_id = request.GET.get('wiki_id')
    if not wiki_id or not wiki_id.isdecimal():
        return render(request, 'personal_management/wiki.html')
    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()

    return render(request, 'personal_management/wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id):
    if request.method == 'GET':
        form = WikiModelForm(request)
        return render(request, 'personal_management/wiki_add.html', {'form': form})
    form = WikiModelForm(request, request.POST)
    if form.is_valid():
        # 判断用户是否选中了父目录
        if form.instance.depth:
            form.instance.depth += 1
        else:
            form.instance.depth = 1
        form.instance.project = request.tracer.project
        form.save()
        url = reverse('websass:wiki', kwargs={'project_id': project_id})
        return redirect(url)
    return render(request, 'personal_management/wiki_add.html', {'form': form})


def wiki_catalog(request, project_id):
    """wiki目录"""
    # data = models.Wiki.objects.filter(project_id=project_id).values_list("id", "title", "parent_id")
    # 这里的data时QuerySet数据，但是我们传到前端的时json数据，所以要转换成list或者字典
    data = models.Wiki.objects.filter(project_id=project_id).values("id", "title", "parent_id").order_by('depth', 'id')
    return JsonResponse({"start": True, "data": list(data)})


def wiki_del(request, project_id, wiki_id):
    """删除文章"""
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    url = reverse('websass:wiki', kwargs={'project_id': project_id})
    return redirect(url)


def wiki_edit(request, project_id, wiki_id):
    """编辑文章"""
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    if not wiki_object:
        url = reverse('websass:wiki', kwargs={'project_id': project_id})
        return redirect(url)
    if request.method == "GET":
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'personal_management/wiki_add.html', {'form': form})
    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        if form.instance.depth:
            form.instance.depth += 1
        else:
            form.instance.depth = 1
        form.save()
        url = reverse('websass:wiki', kwargs={'project_id': project_id})
        preview_url = "{0}?wiki_id={1}".format(url, wiki_id)
        return redirect(preview_url)
    return render(request, 'personal_management/wiki_add.html', {'form': form})


@csrf_exempt  # 由于我们时用markDown进行POST提交没有携带csrf_token,所以加装饰器@csrf_exempt免除csrf_token
def wiki_upload(request, project_id):
    """markDown插件上传图片"""
    result = {
        'success': 0,
        'message': None,
        'url': None,
    }

    image_object = request.FILES.get('editormd-image-file')
    if not image_object:
        result['message'] = '文件不存在'
        return JsonResponse(result)
    ext = image_object.name.rsplit('.')[-1]
    key = "{}.{}".format(uid(request.tracer.user.mobile_phone), ext)
    image_url = upload_file(
        request.tracer.project.bucket,
        request.tracer.project.region,
        image_object,
        key)
    # 给markdown传过去，上传成功，把这个url也传过去
    result['success'] = 1
    result['url'] = image_url

    return JsonResponse(result)
